package com.compass.mobile.ui.activity

import LogUtil
import UserInfoManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.databinding.ActivityAddPatientBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.ADD_PATIENT
import com.compass.mobile.framework.constant.COMMOM_VERIF_CODE
import com.compass.mobile.framework.constant.KEY_PHONE
import com.compass.mobile.framework.constant.REFRESH_PATIENT
import com.compass.mobile.framework.constant.YD_USER_TOKEN
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.CodeUtils.getCodeUrl
import com.compass.mobile.framework.utils.DateUtils
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.PatientDataUtil
import com.compass.mobile.framework.utils.QRCodeDealUtils
import com.compass.mobile.ui.dialog.InputPhoneDialog
import com.compass.mobile.ui.viewModel.UserViewModel
import dp2px
import countDownCoroutines
import getStringFromResource
import kotlinx.coroutines.CoroutineScope

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Description： 绑定就诊人
 * Date:2024/6/20 10:30
 */
class AddPatientActivity : BaseVBActivity<ActivityAddPatientBinding>() {
    private val userViewModel: UserViewModel by viewModels()

    companion object {
        fun start(context: Context, phone: String) {
            val intent = Intent(context, AddPatientActivity::class.java)
            intent.putExtra(KEY_PHONE, phone)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
//        FocusViewUtils.scaleView(mBinding.tvGetCode, 1)
//        FocusViewUtils.scaleView(mBinding.tvSave, 1)
        mBinding.radioSexMail.isChecked = true
        mBinding.topView.setPatientViewVisible(false)

    }

    private var isClick = true
    private var phoneNumber: String? = null
    private var randomStr: String? = null
    private var code: String? = null
    private var mBindType: String = "1"
    private var mOldMobile: String? = null
    private var mOldCode: String? = null
    private var mSelectedValue: Int = -1
    override fun intListener() {
        mBinding.tvGetCode.onClick {
            val phone = mBinding.etPhone.text.toString().trim()

            if (phone.isEmpty()) {
                showToast("请输入手机号")
                return@onClick
            }
            if (isClick) {
                phoneNumber = mBinding.etPhone.text.toString().trim()
                userViewModel.getCode(phoneNumber)
                countDownCoroutines()
            }
        }

//        mBinding.radioSex.setOnCheckedChangeListener { group, checkedId ->
//            val radioButton = findViewById<RadioButton>(checkedId)
//            mSelectedValue = radioButton.text.toString()
//            // 使用selectedValue进行你需要的操作
//        }

        mBinding.etCardno.addTextChangedListener {
            it?.let {
                if (it.isNotEmpty()) {
                    val cardNo = it.toString().trim()
                    //检测正确的身份证，并从输入的身份证号码从提取年龄数据，回填在年龄输入框，如果身份证年龄小于14岁则显示出监护人信息
                    if (PatientDataUtil.checkValidIdNumber(cardNo)) {
                        val age: Int = PatientDataUtil.getAgeByIdNumber(cardNo)
//                        PatientDataUtil.getBirthdayByCardNo(cardNo)
                        if (age > 0) {
                            mBinding.etAge.setText(age.toString())
                        }
                        if (age < PatientDataUtil.UNDERAGE) {
                            mBinding.llGuardian.visible()
                        } else {
                            mBinding.llGuardian.gone()
                        }
                        mSelectedValue = PatientDataUtil.getSexByIdNumber(cardNo)
                        val sex = when (mSelectedValue) {
                            1 -> "男"
                            0 -> "女"
                            else -> "未知"
                        }
                        mBinding.tvSex.setText(sex)

                    } else {
                        mBinding.apply {
                            llGuardian.gone()
                            etAge.setText("")
                            tvSex.setText("输入身份证后自动计算填写")
//                            etGuardianCardno.setText("")
//                            etGuardianPhone.setText("")
//                            etGuardianName.setText("")
                        }
                    }
                } else {
                    mBinding.apply {
                        llGuardian.gone()
                        etGuardianCardno.setText("")
                        etGuardianPhone.setText("")
                        etGuardianName.setText("")
                        etAge.setText("")
                    }

                }
            }
        }
        mBinding.tvSave.onClick {
            phoneNumber = mBinding.etPhone.text.toString().trim()
            code = mBinding.etCode.text.toString().trim()
            val name = mBinding.etName.text.toString().trim()
            val cardNo = mBinding.etCardno.text.toString().trim()
            val age = mBinding.etAge.text.toString().trim()

            var sex = when (mSelectedValue) {
                0 -> 2
                1 -> 1
                else -> 1
            }

            //监护人信息
            val guardianName = mBinding.etGuardianName.text.toString().trim()
            val guardianCardNo = mBinding.etGuardianCardno.text.toString().trim()
            val guardianPhone = mBinding.etGuardianPhone.text.toString().trim()

            //保存
            if (phoneNumber.isNullOrEmpty()) {
                showToast("请输入手机号")
                return@onClick
            }

            if (isCheckCode) {
                if (code.isNullOrEmpty()) {
                    showToast("请输入验证码")
                    return@onClick
                }
            } else {
                code = COMMOM_VERIF_CODE
            }

            if (name.isEmpty()) {
                showToast("请输入姓名")
                return@onClick
            }
            if (cardNo.isEmpty() || !PatientDataUtil.checkValidIdNumber(cardNo)) {
                showToast("请输入正确的身份证号码")
                return@onClick
            }
            if (age.isEmpty()) {
                showToast("请输入年龄")
                return@onClick
            }
//            if(sex.isEmpty()){
//                showToast("请输入性别")
//                return@onClick
//            }
            if (PatientDataUtil.isUnderage(cardNo)) {
                //未成年的情况，需要验证监护人信息
                if (!PatientDataUtil.checkValidIdNumber(guardianCardNo)) {
                    showToast("请输入正确的监护人身份证号")
                    return@onClick
                }

                if (guardianName.isEmpty()) {
                    showToast("请输入正确的监护人姓名")
                    return@onClick
                }

                if (guardianPhone.isEmpty()) {
                    showToast("请输入正确的监护人手机号")
                    return@onClick
                }
            }
            if (mBindType == "3") {
                if (mOldMobile.isNullOrEmpty() || mOldMobile?.length != 11) {
                    showToast("请输入原手机号")
                    return@onClick
                }

                if (mOldMobile.isNullOrEmpty() || mOldMobile?.length != 4) {
                    showToast("请输入原手机号验证码")
                    return@onClick
                }
            }
            showLoading()
            userViewModel.addPatients(
                name,
                cardNo,
                phoneNumber!!,
                code!!,
                sex,
                age,
                mBindType,
                guardianName,
                guardianCardNo,
                guardianPhone,
                mOldMobile,
                mOldCode
            )
        }
    }

    //是否检测验证码
    private var isCheckCode = false
    override fun initData() {
        randomStr = "tv${DateUtils.getToday()}"
        var qrCodeUrl =
              "${ADD_PATIENT}${getCodeUrl()}&randomStr=${randomStr}"

        val phone: String? = intent.getStringExtra(KEY_PHONE)
        qrCodeUrl += if (qrCodeUrl.isEmpty()) {
            "&patientPhone="
        } else {
            "&patientPhone=$phone"
        }
        phone?.let {
            mBinding.etPhone.setText(phone)
//            mBinding.etPhone.setEditableFactory(Editable.)
            mBinding.llVerifCode.gone()
            isCheckCode = false
            mBinding.etPhone.isEnabled = false

        } ?: kotlin.run() {
            mBinding.llVerifCode.visible()
            mBinding.etPhone.isEnabled = true
            isCheckCode = true
        }
        LogUtil.d("qrCodeUrl===$qrCodeUrl")
        mBinding.ivQrcode.setImageBitmap(
            QRCodeDealUtils.generateQRCodeWithoutMargin(
                qrCodeUrl,
                dp2px(400f),
                dp2px(400f)
            )
        )
        userViewModel.addPatientLiveData.observe(this) {
            dismissLoading()
            if (it) {
                LiveDataBus.get().with(REFRESH_PATIENT).postValue(REFRESH_PATIENT)
                //添加成功
                this.finish()
            }
        }

        userViewModel.modifyPatientLiveData.observe(this) {
            if (it) {
                //修改用户数据
                mBindType = "3"
                val inputPhoneDialog =
                    InputPhoneDialog.Builder(this@AddPatientActivity, onPhoneClick)
                inputPhoneDialog.show()
            }
        }
        userViewModel.checkMobileLiveData.observe(this) {
            it?.let { data ->
                isActive = data != "false"
                if (isActive) {
//                   showToast("添加成功")
                    LiveDataBus.get().with(REFRESH_PATIENT).postValue(REFRESH_PATIENT)
                    finish()
                }
            } ?: kotlin.run {
                //接口异常后就不再请求了
                isActive = true
            }

        }

        startPolling(1500)

    }

    private var isActive: Boolean = false
    private fun startPolling(intervalMillis: Long) {
        CoroutineScope(Dispatchers.IO).launch {
            while (!isActive) {
                userViewModel.checkPatient(randomStr)
                delay(intervalMillis) // 暂停一段时间，以轮询间隔继续
            }
        }
    }

    private var onPhoneClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(codeType: Int, msgType: String?) {
            super.onButtonCallBack(codeType, msgType)
            when (codeType) {
                1 -> {
                    //发送验证码
                    mOldMobile = msgType
                }

                2 -> {
                    mOldCode = msgType
                }
            }
        }
    }

    /**
     * 倒计时
     */
    private fun countDownCoroutines() {
        //倒计时
        countDownCoroutines(59, lifecycleScope, onTick = {
            isClick = false
            mBinding.tvGetCode.text =
                getStringFromResource(R.string.sms_tip, it.plus(1).toString())
        }) {
            isClick = true
            mBinding.tvGetCode.text = "获取验证码"
        }
    }


}